package com.ccloud.common.im.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.ccloud.common.im.respo.SessionRepository;
import com.ccloud.common.im.server.CIMNioSocketServer;
import com.ccloud.common.im.model.CIMMsg;
import com.ccloud.common.im.model.CIMSession;
import com.ccloud.common.im.service.CIMSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Service
public class CIMSessionServiceImpl implements CIMSessionService {

    @Resource
    private CIMNioSocketServer nioSocketServer;

    @Resource
    private SessionRepository sessionRepository;

    @Override
    public ConcurrentHashMap<String, ConcurrentHashMap<String, CIMSession>> getSessionMap() {
        return sessionRepository.getSessionMap();
    }

    @Override
    public void save(String userId, String nioId, CIMSession session) {
        sessionRepository.save(userId, nioId, session);
    }

    @Override
    public CIMSession get(String userId, String nioId) {
        CIMSession session = sessionRepository.get(userId, nioId);

        if (session != null) {
            session.setSession(nioSocketServer.getManagedSession(session.getNid()));
        }

        return session;
    }

    @Override
    public void remove(String nioId) {
        sessionRepository.remove(nioId);
    }


    @Override
    public void push(CIMMsg cimMsg, CIMSession session) {
        session.write(cimMsg);
        log.info("[server]已向客户端推送消息:{} ", JSONObject.toJSONString(cimMsg));
    }


}
